package com.hassean.we.admin.common.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;


public class HttpRequest {
	private static Logger logger = Logger.getLogger(HttpRequest.class);
	public static HttpResponse doPost(String url, String jsonObj,String token)
			throws ClientProtocolException, IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-type", "application/json; charset=UTF-8");
		post.setHeader("Authorization",token);
		post.setEntity(new StringEntity(jsonObj, "utf-8"));
		HttpResponse response = client.execute(post);
		return response;
	}


	public static String doGet(String url) throws ClientProtocolException,
			IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			return EntityUtils.toString(entity, "utf-8");
		} else {
			return null;
		}

	}

	public static String doDelete(String url) throws ClientProtocolException,
			IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpDelete del = new HttpDelete(url);
		HttpResponse response = client.execute(del);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			return EntityUtils.toString(entity, "utf-8");
		} else {
			return null;
		}
	}

	public static String doPut(String url, String jsonObj,String token)
			throws ClientProtocolException, IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpPut put = new HttpPut(url);

		put.setEntity(new StringEntity(jsonObj, "utf-8"));
		HttpResponse response = client.execute(put);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			return EntityUtils.toString(entity, "utf-8");
		} else {
			return null;
		}
	}
}